import React,{useState,useEffect} from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input,Select,Modal,message } from 'antd';
import Loading from '@/components/Loading/index.tsx';

import {useNavigate} from 'react-router-dom';

import JSEncrypt from 'jsencrypt'

import './index.global.scss';
import styles from './index.module.scss';
import { req } from '@/common/methods';
import pub from '@/units/pub';


let pushToken = '';

const LoginComponent: React.FC = () => {
    const navigate = useNavigate();
    const [loading,setLoading] = useState(true);
    const [users,setUsers] = useState([]);
    const [buttonDisabled,setButtonDisabled] = useState(false);
    const onFinish = (values: any) => {
        setButtonDisabled(true);
        //console.log('Received values of form: ', values);
        const rand = (Math.floor(Math.random()*61440) + 4096).toString(16);
        //数据加密，请求登录
        const pubkey = pub.getData('pubkey');
        const encrypt = new JSEncrypt();
        encrypt.setPublicKey(pubkey);
        const rsaPassWord = encrypt.encrypt(JSON.stringify({...values,rand,pushToken}));
        //console.log(rsaPassWord);
        req('/api/login',{data:rsaPassWord,validator:rand},'post').then((data)=>{
            message.success('登录成功，欢迎您，' + data.username+'！');
            pub.setData('userid',data.userid);
            pub.setData('username',data.username);
            pub.setData('all_user',data.all_user);
            setButtonDisabled(false);
            setTimeout(()=>{
                navigate('/management/home');
            },1);
        }).catch((error)=>{
            Modal.error({
                title:'登录失败',
                content:<><pre>{''+error}</pre></>
            });
            setButtonDisabled(false);
        });
        
    };
    const fetchBaseData = () => {
        req('/api/user/get_all_for_login').then(data => {
            pushToken = data.no_login_token;
            if(!Array.isArray(data.users)){
                throw '类型校验错误';
            }
            setUsers(data.users);
            setLoading(false);
        }).catch(error => {
            Modal.error({
                title:'错误',
                content:<>初始化页面失败，请尝试刷新或重启，如有故障，请与王阳联系，{''+error}</>
            })
        })
    }
    useEffect(()=>{
        fetchBaseData();
    },[]);
    const handleUsernameSearch = () => {
        //
    }
    const handleUsernameChange = () => {
        //
    }
    const handleUsernameFilterOption = (input: string, option?: { label: string; value: string }) =>
    (option?.label ?? '').toLowerCase().includes(input.toLowerCase());
    return (
    <>
    
        {loading?<Loading/>:<Form
            name="normal_login"
            className={styles['login-form']}
            initialValues={{ remember: true }}
            onFinish={onFinish}
        >
            <Form.Item
                name="username"
                rules={[{ required: true, message: '用户名不能为空' }]}
            >
                {/* <Input prefix={<UserOutlined className={styles["site-form-item-icon"]} />} placeholder="请输入用户名" /> */}
                <Select
                    //prefix={<UserOutlined className={styles["site-form-item-icon"]} />} 
                    //optionFilterProp="children" 
                    showSearch={true}
                    placeholder="请选择用户名"
                    //defaultActiveFirstOption={true}
                    onSearch={handleUsernameSearch}
                    onChange={handleUsernameChange}
                    filterOption={handleUsernameFilterOption}
                    options={users.map ? users.map(item => ({
                        label:item.username,
                        value:item.id,
                        key:item.id
                    })) : []}
                />
            </Form.Item>
            <div className={styles.lin}></div>
            <Form.Item
                name="password"
                rules={[{ required: true, message: '密码不能为空' }]}
            >
                <Input
                    prefix={<LockOutlined className={styles["site-form-item-icon"]} />}
                    type="password"
                    placeholder="请输入密码"
                />
            </Form.Item>
            <Form.Item>
                <div className={styles['login-extra-pkg']}>
                    <div>
                        <Form.Item name="remember" valuePropName="checked" noStyle>
                            <Checkbox>自动登录</Checkbox>
                        </Form.Item>
                    </div>
                    <a className={styles['login-form-forgot']} href="" onClick={(e)=>{
                        e?.preventDefault();
                        Modal.info({
                            title:'找回密码',
                            content:<>
                                功能未启用
                            </>
                        })
                    }}>忘记密码</a>
                </div>

            </Form.Item>

            <Form.Item>
                <Button type="primary" htmlType="submit" className={styles['login-form-button']} disabled={buttonDisabled} loading={buttonDisabled}>
                    登录
                </Button>
            </Form.Item>
        </Form>}
    </>
  );
};

export default LoginComponent;